package com.homework.module6part1.controller;

import com.homework.dao.domain.Order;
import com.homework.module6part1.service.OrderService;
import com.homework.util.ResultMsg;
import com.homework.util.ResultUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class RabbitmqController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private AmqpTemplate rabbitTemplate;

    //首页
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    //下单
    @RequestMapping(value = "/order", method = {RequestMethod.POST})
    @ResponseBody
    public ResultMsg order() {
        //1.生成订单
        Order order = orderService.addOrder();
        //2.发送带有ttl的msg
        rabbitTemplate.convertAndSend("ex.go", "go", order.getId());

        return ResultUtil.success(order.getId());
    }

    //支付页面
    @RequestMapping(value = "/paypage/{id}", method = {RequestMethod.GET})
    public ModelAndView paypage(@PathVariable("id") int id) {
        ModelAndView modelAndView = new ModelAndView("pay");
        modelAndView.addObject("orderId", id);
        return modelAndView;
    }

    //支付
    @RequestMapping(value = "/pay/{id}", method = {RequestMethod.POST})
    @ResponseBody
    public ResultMsg pay(@PathVariable("id") int id) {
        orderService.setOrderPayed(id);
        return ResultUtil.success();
    }

    //我的订单详情
    @RequestMapping("/detail/{id}")
    public ModelAndView detail(@PathVariable("id") int id) {
        ModelAndView modelAndView = new ModelAndView("detail");
        modelAndView.addObject("orderDetail", orderService.getOrder(id));

        return modelAndView;
    }

    //未支付列表
    @RequestMapping("/unpaylist")
    public ModelAndView unpayList() {
        List<Order> unpayList = orderService.getExpireOrders();
        ModelAndView modelAndView = new ModelAndView("unpaylist");
        modelAndView.addObject("list", unpayList);

        return modelAndView;
    }
}
